
#include "bullets.h"
#include "gopaupau.h"

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <GL/gl.h>


void bulletDisable(Bullet *toBeRemoved, Bullet *prev)
{
	if(prev==NULL) // head to be removed
		bullets_enabled_head = toBeRemoved->next;
	else
	  prev->next = toBeRemoved->next;
	  
	toBeRemoved->next = bullets_disabled_head;
	bullets_disabled_head = toBeRemoved;
}


Bullet *moreBullets(int listSize)
{
	Bullet *head = NULL;
	int loop;
	Bullet *tmp;

    for(loop=0; loop<listSize; loop++)
    {

		if ((tmp = malloc(sizeof(*tmp))) == NULL) {
      		printf("failed to alloc memory for bullets\n");
      		(void)exit(EXIT_FAILURE);
    	}

    	tmp->x = 0.0f;
    	tmp->y = 0.0f;
    	tmp->direction = 0.0f;
    	tmp->speed = 1.0;
    	
    	tmp->next = head;
    	head = tmp;
    }
    return(head);
}

Bullet *bulletGetNew() 
{
	if(bullets_disabled_head==NULL)
	{
		bullets_disabled_head = moreBullets(5);
	}
	Bullet *tmp = bullets_enabled_head;
	bullets_enabled_head = bullets_disabled_head;
	bullets_disabled_head = bullets_disabled_head->next;
	bullets_enabled_head->next = tmp;
	bullets_enabled_head->speed_d = 0.0f;
	return bullets_enabled_head;
}


void bulletsInit(int listSize)
{
	bullets_enabled_head = NULL;
	bullets_disabled_head = moreBullets(listSize);
}


void bulletsPrint()
{
	Bullet *tmp;
	int c=1;
	printf("Enabled bullets:\n");
	if(bullets_enabled_head==NULL) printf("none\n");
	else
	{
		tmp = bullets_enabled_head;
		while(tmp!=NULL)
		{
			printf("%d: %f %f next=%d\n", c++, tmp->x, tmp->y, (int)tmp->next);
			tmp = tmp->next;
		}
	}
	c=1;
	printf("Disabled bullets:\n");
	if(bullets_disabled_head==NULL) printf("none\n");
	else
	{
		tmp = bullets_disabled_head;
		while(tmp!=NULL)
		{
			printf("%d: %f %f next=%d\n", c++, tmp->x, tmp->y, (int)tmp->next);
			tmp = tmp->next;
		}
	}		
}

void bulletsDrawUpdate()
{
	Bullet *bul;
	Bullet *prev = NULL;
	bul = bullets_enabled_head;
	glColor3f(1.0f,0.0f,0.3f);
  
	while(bul!=NULL)
	{
		float xd = bul->x - player.x;
		float yd = bul->y - player.y;
		if(xd<5.0f && xd>-5.0f)
			if(yd<5.0f && yd>-5.0f)
				playerAlive=0;
		
		
		glLoadIdentity();
		bul->x+=cos(bul->direction/180 * 3.1459f)*bul->speed;
		bul->y+=sin(bul->direction/180 * 3.1459f)*bul->speed;
		glTranslatef(bul->x,bul->y,0.0f);
		glBegin(GL_POLYGON);
		glVertex2d(1,-3);
		glVertex2d(3, -1);
		glVertex2d(3, 1);
		glVertex2d(1,3);
		glVertex2d(-1,3);
		glVertex2d(-3,1);
		glVertex2d(-3,-1);
		glVertex2d(-1,-3);
		glEnd();
	
		bul->speed += bul->speed_d / (1 / (bul->speed*bul->speed));
	  	if(bul->x < 0 || bul->x > 680 || bul->y < 0 || bul->y > 480)
	  	{
	  		bulletDisable(bul, prev);
	  		if(prev!=NULL)
	  			bul = prev->next;
	  		else
	  			bul = bullets_enabled_head;
	  	}
	  	else
	  	{
	  		prev = bul;
	  		bul = bul->next;
	    }	
	}
}	



